package com.bigfans.catalogservice.service.productgroup;

import com.bigfans.catalogservice.dao.ProductGroupAttributeDAO;
import com.bigfans.catalogservice.dao.ProductGroupDAO;
import com.bigfans.catalogservice.model.*;
import com.bigfans.catalogservice.service.attribute.AttributeOptionService;
import com.bigfans.catalogservice.service.attribute.AttributeValueService;
import com.bigfans.catalogservice.service.brand.BrandService;
import com.bigfans.catalogservice.service.category.CategoryService;
import com.bigfans.catalogservice.service.product.ProductService;
import com.bigfans.catalogservice.service.tag.TagService;
import com.bigfans.framework.cache.Cacheable;
import com.bigfans.framework.dao.BaseServiceImpl;
import com.bigfans.framework.exception.ServiceRuntimeException;
import com.bigfans.framework.model.PageBean;
import com.bigfans.framework.utils.CollectionUtils;
import com.bigfans.framework.utils.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品组服务类
 *
 * @author lichong
 */
@Service(ProductGroupServiceImpl.BEAN_NAME)
public class ProductGroupServiceImpl extends BaseServiceImpl<ProductGroup> implements ProductGroupService {

    public static final String BEAN_NAME = "productGroupService";

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductService productService;
    @Autowired
    private TagService tagService;
    @Autowired
    private ProductGroupAttributeDAO productGroupAttributeDAO;
    @Autowired
    private AttributeOptionService attributeOptionService;
    @Autowired
    private AttributeValueService attributeValueService;
    @Autowired
    private BrandService brandService;

    private ProductGroupDAO productGroupDAO;

    @Autowired
    public ProductGroupServiceImpl(ProductGroupDAO productGroupDAO) {
        super(productGroupDAO);
        this.productGroupDAO = productGroupDAO;
    }

    @Override
    @Transactional
    public void create(ProductGroup pg, List<Product> products, List<ProductGroupAttribute> pgAttrs)
            throws Exception {
        this.create(pg, products, pgAttrs, null);
    }

    @Override
    @Transactional
    public void create(ProductGroup pg, List<Product> products, List<ProductGroupAttribute> pgAttrs, List<ProductGroupTag> tags)
            throws Exception {
        // 创建商品组
        super.create(pg);
        // 创建标签，用于搜索提示
        if (tags == null) {
            tags = new ArrayList<>();
        }
        // 将品牌名称默认添加为一个标签
        if (StringHelper.isNotEmpty(pg.getBrandId())) {
            Brand brand = brandService.load(pg.getBrandId());
            ProductGroupTag brandTag = new ProductGroupTag();
            brandTag.setValue(brand.getName());
            tags.add(brandTag);
        }
        for (ProductGroupTag pgt : tags) {
            pgt.setProdCount(products.size());
            pgt.setPgId(pg.getId());
            if (pgt.isNew()) {
                List<Tag> duplicates = tagService.listDuplicate(pgt.getValue());
                if (CollectionUtils.isEmpty(duplicates)) {
                    Tag t = new Tag();
                    t.setName(pgt.getValue());
                    tagService.create(t);
                    pgt.setTagId(t.getId());
                } else if (duplicates.size() == 1) {
                    pgt.setTagId(duplicates.get(0).getId());
                } else if (duplicates.size() > 1) {
                    String tagId = tagService.mergeDuplicates(duplicates);
                    pgt.setTagId(tagId);
                }
            }
        }
        this.saveRelationship(tags);

        // 创建规格
        if (pgAttrs != null) {
            for (ProductGroupAttribute pga : pgAttrs) {
                pga.setPgId(pg.getId());
                String optionId = pga.getOptionId();
                String value = pga.getValue();
                AttributeOption attrOption = attributeOptionService.load(optionId);
                if (attrOption.getRequired() && StringHelper.isEmpty(pga.getValue())) {
					throw new ServiceRuntimeException("属性不能为空: " + attrOption.getName());
                }
                switch (attrOption.getInputType()) {
                    // 如果规格值是手动输入的,那么先创建规格值,传递过来的值为输入的内容
                    case AttributeOption.INPUTTYPE_MANUL:
                        AttributeValue av = new AttributeValue();
                        av.setCategoryId(pg.getCategoryId());
                        av.setOptionId(optionId);
                        av.setValue(value);
                        attributeValueService.create(av);
                        pga.setValueId(av.getId());
                        break;
                    // 如果是选择已存在的规格值,那么设置valueId,传递过来的值为选择的ID
                    case AttributeOption.INPUTTYPE_LIST:
                        pga.setValueId(value);
                        break;
                    default:
                        break;
                }
            }
            productGroupAttributeDAO.batchInsert(pgAttrs);
        }
        // 创建商品信息
        for (Product prod : products) {
            prod.setName(pg.getName());
            prod.setOrigin(pg.getOrigin());
            prod.setBrandId(pg.getBrandId());
            prod.setPgId(pg.getId());
            prod.setCategoryId(pg.getCategoryId());
            productService.create(prod, prod.getImgList(), prod.getSpecList());
        }
    }

    @Override
    @Cacheable
    @Transactional(readOnly = true)
    public List<ProductGroupAttribute> listAttributeById(String productGroupId) throws Exception {
        ProductGroup productGroup = super.load(productGroupId);

        List<ProductGroupAttribute> attributes = new ArrayList<ProductGroupAttribute>();

        ProductGroupAttribute catAttr = new ProductGroupAttribute();
        catAttr.setOptionName("商品分类");
        catAttr.setValue(productGroup.getCategoryName());

        ProductGroupAttribute brandAttr = new ProductGroupAttribute();
        brandAttr.setOptionName("品牌");
        brandAttr.setValue(productGroup.getBrandName());

        attributes.add(catAttr);
        attributes.add(brandAttr);

        List<ProductGroupAttribute> pgAttributes = productGroupAttributeDAO.listByPgId(productGroupId);
        attributes.addAll(pgAttributes);

        return attributes;
    }

    @Override
    @Transactional(readOnly = true)
    public PageBean<ProductGroup> pageByCategory(String catId, Long start, Long pagesize) throws Exception {
        return productGroupDAO.pageByCategoryId(new String[]{catId}, start, pagesize);
    }

    @Transactional(readOnly = true)
    public String getDescription(String pgId) {
        return productGroupDAO.getDescription(pgId);
    }

    @Override
    @Transactional(readOnly = true)
    public String getDescriptionByProd(String prodId) throws Exception {
        Product product = productService.load(prodId);
        return productGroupDAO.getDescription(product.getPgId());
    }
}
